<?php

namespace addons\groupon\library\traits\model\order;

use addons\groupon\exception\Exception;
use addons\groupon\model\Dispatch;
use addons\groupon\model\DispatchAutosend;
use addons\groupon\model\DispatchSelfetch;
use addons\groupon\model\DispatchStore;
use addons\groupon\model\Goods;
use addons\groupon\model\Verify;
use addons\groupon\model\User;
use addons\groupon\model\Order;
use addons\groupon\model\OrderAction;
use addons\groupon\model\OrderItem;
use addons\groupon\model\Store;
use think\Cache;
use think\Db;

trait OrderOperSendGet
{
    
    /**
     * 团长到货
     */
    public function storeArrive($express, $orders)
    {
        $store = Store::info();

        foreach ($orders as $key => $order) {
            $this->storeArriveItem($express, $order, ['oper_type' => 'store', 'oper' => $store]);
        }
    }


    // 团长到货
    public function storeArriveItem($express, $order, $data = [])
    {
        // 订单到货前
        $hookData = ['order' => $order, 'express' => $express];
        \think\Hook::listen('groupon_order_arrive_before', $hookData);

        foreach ($order['item'] as $key => $item) {
            $extData = ['arrive_time' => time()];
            if (isset($data['ext']) && $data['ext']) {
                $extData = array_merge($extData, $data['ext']);
            }
            $item->ext = json_encode($item->setExt($item, $extData));
            
            $item->dispatch_status = \addons\groupon\model\OrderItem::DISPATCH_STATUS_ARRIVE;    // 已到貨状态
            $item->save();
            
            $oper_type = $data['oper_type'] ?? 'system';
            $oper = $data['oper'] ?? null;
            extract($this->getOper($oper_type, $oper));
    
            \addons\groupon\model\OrderAction::operAdd($order, $item, $oper, $oper_type, $oper_iden . '到货订单');
        }

        // 订单到貨后
        $hookData = ['order' => $order, 'express' => $express];
        \think\Hook::listen('groupon_order_arrive_after', $hookData);

        return $item;
    }


    // 給团长发货
    public function sendItemToStore($order, $item, $data = [])
    {
        // 订单发货前
        $hookData = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_send_before', $hookData);

        $item->store_express_id = $data['store_express_id'] ?? null;

        $extData = ['ready_time' => time()];
        if (isset($data['ext']) && $data['ext']) {
            $extData = array_merge($extData, $data['ext']);
        }
        $item->ext = json_encode($item->setExt($item, $extData));

        $item->dispatch_status = \addons\groupon\model\OrderItem::DISPATCH_STATUS_READY;    // 已备货状态
        $item->save();

        $oper_type = $data['oper_type'] ?? 'system';
        $oper = $data['oper'] ?? null;
        extract($this->getOper($oper_type, $oper));

        \addons\groupon\model\OrderAction::operAdd($order, $item, $oper, $oper_type, $oper_iden . '备货订单');

        // 生成核销码
        $this->createVerify($order, $item, [
            'expiretime' => time() + (5 * 86400)        // 默认五天到期
        ]);

        // 订单发货后
        $hookData = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_send_after', $hookData);

        return $item;
    }



    /**
     * 核销二维码并确认收货
     */
    public function verifyGeted($order, $item, $verify = null, $data = [])
    {
        // 获取操作人
        $oper_type = $data['oper_type'] ?? 'system';
        $oper = $data['oper'] ?? null;
        extract($this->getOper($oper_type, $oper));

        // 使用掉核销券
        if ($verify) {
            $verify->usetime = time();
            $verify->oper_type = $oper_type;
            $verify->oper_id = $oper ? (is_array($oper) ? $oper['id'] : $oper->id) : 0;
            $verify->save();
        }

        // 查询当前订单 item 所有核销券
        $verifiy_num = Verify::canUse()->where('order_item_id', $item['id'])
            ->where('type', 'verify')
            ->count();

        // 判断所有核销码全部核销才能确认收货
        if (!$verifiy_num) {
            // 没有可用优惠券，订单收货
            $this->getedItem($order, $item, $data);
        }
    }



    /**
     * 收货订单
     */
    public function getedItem($order, $item, $data = [])
    {
        // 订单确认收货前
        $hookData = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_confirm_before', $hookData);

        $ext = ['confirm_time' => time()];
        if (isset($data['ext']) && $data['ext']) {
            $ext = array_merge($ext, $data['ext']);
        }
        $item->ext = json_encode($item->setExt($item, $ext));
        $item->dispatch_status = OrderItem::DISPATCH_STATUS_GETED;        // 确认收货
        $item->save();

        $oper_type = $data['oper_type'] ?? 'system';
        $oper = $data['oper'] ?? null;
        extract($this->getOper($oper_type, $oper));
        OrderAction::operAdd($order, $item, $oper, $oper_type, $oper_iden . '确认收货');

        // 订单确认收货后
        $hookData = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_confirm_after', $hookData);

        return $order;
    }


    /**
     * 生成码
     */
    private function createVerify($order, $item = null, $data = [])
    {
        $verify = new Verify();

        $verify->user_id = $order['user_id'];
        $verify->type = 'verify';

        $verify->order_id = $order['id'];
        $verify->order_item_id = $item['id'] ?? 0;
        $verify->expiretime = $data['expiretime'];

        $i = 0;
        do {
            // 循环生成唯一核销码
            $is_error = false;
            try {
                $verify->code = Verify::getCode();
                $verify->save();
            } catch (\think\exception\PDOException $e) {
                if ($e->getCode() == '10501') {
                    $is_error = true;
                }
                $i++;

                if ($i > 5) {
                    if (strpos(request()->url(), 'addons') !== false) {
                        // 接口响应
                        new Exception('核销码生成失败');
                    } else {
                        // 后台响应
                        throw new \Exception('核销码生成失败');
                    }
                }
            }
        } while ($is_error);
    }


    /**
     * 根据 oper_type 获取对应的用户
     */
    private function getOper($oper_type, $origin_oper = null)
    {
        $oper = null;
        $oper_iden = '系统自动';
        if ($oper_type == 'system') {
            // 系统自动操作
            $oper = null;
            $oper_iden = '系统自动';
        } else if ($oper_type == 'user') {
            // 用户操作
            $oper = $origin_oper ?: User::info();
            $oper_iden = '用户';
        } else if ($oper_type == 'admin') {
            // 管理员操作
            $oper = $origin_oper ?: null;
            $oper_iden = '管理员';
        } else if ($oper_type == 'store') {
            // 门店管理员操作
            $oper = $origin_oper ?: Store::info();
            $oper_iden = '门店管理员';
        }

        return compact("oper", "oper_iden");
    }
}
